//
//  LoginViewController.m
//  HengHuaSupervision
//
//  Created by XD-XY on 3/23/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "LoginViewController.h"
#import "XDHeader.h"
#import "XDTools.h"
#import "Request.h"
#import "Response.h"
#import "MyFile.h"
#import "JSONKit.h"
#import "UserInfo.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //1071 676 60 64 20 136 139 144
    
    //视图背景
    bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.width)];
    bgView.image = mLogin_Bg_Img;
    bgView.userInteractionEnabled= YES;
    [self.view addSubview:bgView];
    
    //输入框背景图片
    UIImageView * insertBg = [[UIImageView alloc] initWithFrame:CGRectMake(676/2.0f, 1071/2.0f, mLogin_Input_Img.size.width,mLogin_Input_Img.size.height)];
    insertBg.userInteractionEnabled =YES;
    insertBg.image = mLogin_Input_Img;
    [bgView addSubview:insertBg];
    
    //输入框
    mytextField = [[UITextField alloc] initWithFrame:CGRectMake(152/2.0f, 0, 530/2.0f, insertBg.frame.size.height)];
    mytextField.backgroundColor = [UIColor clearColor];
    mytextField.placeholder = @"请输入您设备的唯一标示";
    mytextField.clearButtonMode =UITextFieldViewModeAlways;
    mytextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    mytextField.font = [UIFont systemFontOfSize:20];
    mytextField.delegate = self;
    [insertBg addSubview:mytextField];
    
    //new
    if(IS_NOT_EMPTY([XDTools readPassWord])){
        mytextField.text = [XDTools readPassWord];
    }
    //end
    
    //确定按钮
    UIButton * suerBtn = [UIButton initButton:CGRectMake(insertBg.frame.origin.x, height_y(insertBg)+30, mLogin_Sure_Normal_Img.size.width, mLogin_Sure_Normal_Img.size.height) btnNorImage:mLogin_Sure_Normal_Img btnPressBtn:mLogin_Sure_Highlight_Img btnTitle:nil titleColor:nil titleFont:nil];
    [suerBtn addTarget:self action:@selector(goToLogin) forControlEvents:UIControlEventTouchDown];
    [bgView addSubview:suerBtn];
}

#pragma mark =====================UITextFiled Delegate===================
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self changeBgview:NO];
    [textField resignFirstResponder];
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [self changeBgview:YES];
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self changeBgview:NO];
    DDLOG_CURRENT_METHOD;
}


//键盘控制scrollview的偏移动画
-(void)changeBgview:(BOOL)ischange
{
    if (ischange){
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        bgView.frame = CGRectMake(0, -340,mLogin_Bg_Img.size.width,mLogin_Bg_Img.size.height);
        [UIView commitAnimations];
    }else{
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.1];
        bgView.frame = CGRectMake(0, 0,mLogin_Bg_Img.size.width,mLogin_Bg_Img.size.height);
        [UIView commitAnimations];
    }
}

-(void)goToLogin{
    [self changeBgview:NO];
    [mytextField resignFirstResponder];
    [XDTools sharedXDTools].ud = mytextField.text;
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isChangeuuid"];
    if (mytextField.text.length!=0&&mytextField.text != nil) {
        BOOL isfirst = [[NSUserDefaults standardUserDefaults] boolForKey:@"isFirstStart"];
        if(isfirst){
            [self Login];;
        }else{
            if (![[XDTools readPassWord] isEqualToString:mytextField.text]){
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isChangeuuid"];
                UIAlertView * alert  = [[UIAlertView alloc] initWithTitle:@"更改设备号会重置数据,请慎重操作" message:nil delegate:self cancelButtonTitle:@"继续" otherButtonTitles:@"取消", nil];
                [alert show];
                return;
            }
            NSDictionary * dict = [[NSUserDefaults standardUserDefaults] valueForKey:@"USERINFOS"];
            [[UserInfo sharedUserInfo] setValueWithDictionary:dict];
            [XDTools savePassWord:[UserInfo sharedUserInfo].udid];
            [[XDTools appDelegate] reSetRootView];
        }
    }else{
        [XDTools showTips:@"设备标示不能为空" toView:self.view];
    }
}

#pragma mark =====================登录=========================
-(void)Login
{
    Request * loginRequest = [[Request alloc] init];
    NSString *jsonStr = [NSString stringWithFormat:@"{\"udid\":%@}",mytextField.text];
    [XDTools sharedXDTools].ud = mytextField.text;
    NSDictionary* requestEntity = [jsonStr objectFromJSONString];
    [XDTools showProgress:[UIApplication sharedApplication].keyWindow];
    [loginRequest request:mTrace_LoginUrl keyValue:requestEntity completionHandler:^(ResponseData *data) {
        if([data.result intValue]==1){
            [XDTools hideProgress:[UIApplication sharedApplication].keyWindow];
            NSDictionary * dic = [XDTools JSonFromString:data.responseJson];
            
            NSDictionary * ddd = [dic valueForKey:@"content"];
            if ([ddd.allValues count] == 0){
                return;
            }
            [[NSUserDefaults standardUserDefaults] setValue:ddd forKey:@"USERINFOS"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[UserInfo sharedUserInfo] setValueWithDictionary:[dic valueForKey:@"content"]];
            [XDTools savePassWord:[UserInfo sharedUserInfo].udid];
            [UserInfo sharedUserInfo].isLogIn = @"1";
            //new
            [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"isLogin"];
            //end
            [[XDTools appDelegate] reSetRootView];
        }else{
            [XDTools hideProgress:[UIApplication sharedApplication].keyWindow];
            DDLOG(@"%@",data.errorMsg);
            [XDTools showTips:data.errorMsg toView:self.view];
        }
    }];
   //   [[XDTools appDelegate] reSetRootView];
    DDLOG_CURRENT_METHOD;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0){
        [self Login];
    }
    DDLOG(@"buttonIndex = %d",buttonIndex);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
